import * as Taro from '@tarojs/taro'
import { IResponse } from './base'
import { config } from './config'

interface WechatLoginRequest {
  code: string
  nickname?: string
  avatarUrl?: string
}

interface WechatLoginResponse {
  accessToken: string
  refreshToken: string
  tokenType: string
  expiresIn: number
  userId: number
  nickname: string
  avatarUrl: string
  isNewUser?: boolean
  openid: string
  unionid: string
  session_key: string
}

interface WechatProfileLoginRequest {
  code: string
  encryptedData: string
  iv: string
}

export class AuthService {
  static baseURL = config.baseURL
  static timeout = config.timeout
  static async wechatLogin(): Promise<WechatLoginResponse> {
    try {
      // 1. 获取微信授权码
      const { code } = await Taro.login()

      // 2. 获取用户信息（可选）
      let userInfo = {}
      try {
        const { userInfo: info } = await Taro.getUserInfo()
        userInfo = {
          nickname: info.nickName,
          avatarUrl: info.avatarUrl,
        }
      } catch (error) {
        console.warn('获取用户信息失败，使用默认信息', error)
      }

      // 3. 调用后端登录接口
      const requestData: WechatLoginRequest = {
        code,
        ...userInfo,
      }

      const response = await Taro.request<IResponse<WechatLoginResponse>>({
        url: `${AuthService.baseURL}/api/wechat/login`,
        method: 'POST',
        data: requestData,
        header: {
          'Content-Type': 'application/json',
        },
        timeout: AuthService.timeout,
      })

      if (response.statusCode === 200 && response.data.code === 200) {
        const loginData = response.data.data

        // 保存令牌到本地存储
        await Taro.setStorage({
          key: 'accessToken',
          data: loginData.accessToken,
        })

        await Taro.setStorage({
          key: 'refreshToken',
          data: loginData.refreshToken,
        })

        return loginData
      } else {
        throw new Error(response.data.message || '登录失败')
      }
    } catch (error) {
      console.error('微信登录失败:', error)
      throw error
    }
  }

  // 刷新令牌
  static async refreshToken(): Promise<WechatLoginResponse> {
    const refreshToken = await Taro.getStorage({ key: 'refreshToken' })

    const response = await Taro.request({
      url: `${AuthService.baseURL}/wechat/refresh`,
      method: 'POST',
      header: {
        Authorization: `Bearer ${refreshToken.data}`,
        'Content-Type': 'application/json',
      },
    })

    if (response.statusCode === 200) {
      const loginData = response.data.data
      await Taro.setStorage({
        key: 'accessToken',
        data: loginData.accessToken,
      })
      return loginData
    } else {
      throw new Error('刷新令牌失败')
    }
  }

  static async wechatProfileLogin({ encryptedData, iv }: { encryptedData: string; iv: string }) {
    try {
      // 1. 获取微信登录凭证
      const loginRes = await Taro.login()
      if (!loginRes.code) {
        throw new Error('获取微信登录凭证失败')
      }

      if (!encryptedData || !iv) {
        throw new Error('获取用户信息失败')
      }

      const requestData: WechatProfileLoginRequest = {
        code: loginRes.code,
        encryptedData: encryptedData,
        iv: iv,
      }

      const response = await Taro.request<IResponse<WechatLoginResponse>, WechatProfileLoginRequest>({
        url: `${AuthService.baseURL}/wechat/auth-login`,
        method: 'POST',
        data: requestData,
        header: {
          'Content-Type': 'application/json',
        },
        timeout: AuthService.timeout,
      })
      if (response.statusCode === 200 && response.data.code === 200) {
        const loginData = response.data.data

        // 保存令牌到本地存储
        await Taro.setStorage({
          key: 'accessToken',
          data: loginData.accessToken,
        })

        return loginData
      } else {
        throw new Error(response.data.message || '登录失败')
      }
    } catch (error) {
      console.error('微信登录失败:', error)
      throw error
    }
  }
}
